package com.gy.assistant.ui.chat.room;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.HashMap;

import im.zego.zim.ZIM;
import im.zego.zim.callback.ZIMRoomAttributesQueriedCallback;
import im.zego.zim.callback.ZIMRoomMemberQueriedCallback;
import im.zego.zim.entity.ZIMError;
import im.zego.zim.entity.ZIMRoomMemberQueryConfig;
import im.zego.zim.entity.ZIMUserInfo;
import com.gy.assistant.R;
import com.gy.assistant.SDKManager;
import com.gy.assistant.enums.MessageLoadType;
import com.gy.assistant.ui.BaseActivity;
import com.gy.assistant.ui.MainActivity;
import com.gy.assistant.ui.chat.room.adapter.RoomMemberListAdapter;


public class ZIMRoomMemberActivity extends BaseActivity implements ZIMRoomMemberQueriedCallback, ZIMRoomAttributesQueriedCallback {

    public static final String ROOM_NOTICE_ATTR = "RoomNotice";
    private TextView roomNoticeTextView;
    private ImageView roomNoticeImageView;
    private RecyclerView recyclerView;
    private RoomMemberListAdapter memberListAdapter = new RoomMemberListAdapter();
    private String queryNextFlag;
    private int QUERY_MEMBER_COUNT = 30;
    private String roomID;
    private MessageLoadType messageLoadType;

    public static void actionStart(Activity loginActivity, String roomID) {
        Intent intent = new Intent(loginActivity, ZIMRoomMemberActivity.class);
        intent.putExtra("roomID", roomID);
        loginActivity.startActivity(intent);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        roomID = getIntent().getStringExtra("roomID");
        setContentView(R.layout.activity_room_member);

        bindView();
        setEventHandler();

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void bindView() {
        roomNoticeTextView = findViewById(R.id.room_notice);
        roomNoticeImageView = findViewById(R.id.room_notice_update_icon);

        String ownerUserID = ZIMRoomChatActivity.RoomOwnerMap.get(roomID);
        if (ownerUserID != null && ownerUserID.equals(SDKManager.sharedInstance().zimUserInfo.userID)) {
            LinearLayout roomNoticeLayout = findViewById(R.id.room_notice_layout);
            roomNoticeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ZIMRoomNoticeUpdateActivity.actionStart(ZIMRoomMemberActivity.this, roomID, roomNoticeTextView.getText().toString());
                }
            });
        } else {
            roomNoticeImageView.setVisibility(View.GONE);
        }

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView = findViewById(R.id.room_member_list);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(memberListAdapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == memberListAdapter.getItemCount()) {
                    if (messageLoadType != MessageLoadType.MESSAGE_LOAD_TYPE_LOADING && messageLoadType != MessageLoadType.MESSAGE_LOAD_TYPE_NO_DATA) {
                        queryMemberList();
                    }
                }
            }
        });
    }

    private void setEventHandler() {
        queryMemberList();
        SDKManager.sharedInstance().queryRoomAllAttributes(roomID, this);
        SDKManager.sharedInstance().setRoomMemberLeftCallback(new SDKManager.OnRoomMemberLeftCallback() {
            @Override
            public void onRoomMemberLeft(ZIM zim, ArrayList<ZIMUserInfo> memberList, String roomID) {
                ZIMRoomMemberActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            memberListAdapter.deleteAll(memberList);
                        }
                    }
                });
            }
        });
        SDKManager.sharedInstance().setRoomMemberJoinCallback(new SDKManager.OnRoomMemberJoinCallback() {
            @Override
            public void onRoomMemberJoinCallback(ZIM zim, ArrayList<ZIMUserInfo> memberList, String roomID) {
                ZIMRoomMemberActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            memberListAdapter.addAll(memberList);
                        }
                    }
                });
            }
        });
    }

    private void queryMemberList() {
        messageLoadType = MessageLoadType.MESSAGE_LOAD_TYPE_LOADING;
        ZIMRoomMemberQueryConfig zimRoomMemberQueryConfig = new ZIMRoomMemberQueryConfig();
        zimRoomMemberQueryConfig.count = QUERY_MEMBER_COUNT;
        zimRoomMemberQueryConfig.nextFlag = queryNextFlag;
        SDKManager.sharedInstance().queryRoomMember(roomID, zimRoomMemberQueryConfig, ZIMRoomMemberActivity.this);
    }

    public void onQuitRoom(View view) {
        SDKManager.sharedInstance().leaveRoom(roomID);

        Intent intent = new Intent(ZIMRoomMemberActivity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

    @Override
    public void onRoomAttributesQueried(String roomID, HashMap<String, String> roomAttributes, ZIMError errorInfo) {
        if (roomAttributes != null) {
            String roomNotice = roomAttributes.get(ROOM_NOTICE_ATTR);
            roomNoticeTextView.setText(roomNotice);
        }
    }

    @Override
    public void onRoomMemberQueried(String roomID, ArrayList<ZIMUserInfo> memberList, String nextFlag, ZIMError errorInfo) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                memberListAdapter.addAll(memberList);
                queryNextFlag = nextFlag;
                if (nextFlag == null || nextFlag.equals("")) {
                    messageLoadType = MessageLoadType.MESSAGE_LOAD_TYPE_NO_DATA;
                } else {
                    messageLoadType = MessageLoadType.MESSAGE_LOAD_TYPE_LOAD_COMPLETE;
                }
            }
        });
    }
}
